import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
  SearchOutlined,
  UndoOutlined
} from '@ant-design/icons';
import {
  Button,
  message,
  Form,
  Modal,
  Upload,
  UploadProps,
  Row,
  Col,
  Input,
  Popconfirm,
  Select,
  Image,
  Radio,
  TreeSelect, UploadFile,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import '@/assets/css/index.less';
import {
  approvePhoto,
  changePhotoOrder,
  deletePhotoByPhoId,
  getPhotoCategoryList,
  getPhotoFile,
  getPhotoListWithoutSpe,
} from '@/services/pictureManager';
import { history, useModel } from 'umi';
import formatDate from '@/utils/formatDate';
import { authorOptions, statusOptions, timeOptions } from '../options';
import {ProForm, ProFormItem} from '@ant-design/pro-components';
import { getPhoCatListWithoutSpe } from '@/services/category';
import {ModalForm, ProFormText} from "@ant-design/pro-form";
import {addWhiteList, updateWhiteList} from "@/services/ipLimit";
import MultiImgUpload from "@/components/multiImgUpload";
import ImgUpload from "@/components/ImgUploadByParam";
import {
  addSubSystem,
  delSubSystem,
  getRoleList,
  getSubSystem,
  getSubSystemList,
  updateSubSystem
} from "@/services/subSystem";
import {BASE_URL} from "../../../../proxyConfig";

const MNTPrefix = BASE_URL;


const PicturenManagement: React.FC = () => {
  const [form] = Form.useForm();
  const { initialState } = useModel('@@initialState');
  const formLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [picForm, setPicForm] = useState({});
  useEffect(()=>{
    console.log(fileList);
    if(fileList[0]?.response?.data[0]){
      form.setFieldValue('pic',fileList[0]?.response.data[0].src)
      setPicForm(fileList[0]?.response.data[0])
      console.log(picForm);
    }else if(fileList[0]?.src){

    }else{
      form.setFieldValue('pic','')
      setPicForm({})
    }
  },[fileList])
  const { currentUser } = initialState || {};
  const _initSearchForm = () => {
    return (
      <div className="ant-pro-table-search ant-pro-table-search-query-filter">
        <Form
          form={form}
          className="ant-form ant-form-horizontal ant-pro-form-query-filter"
          layout="inline"
        >
          <Row style={{ width: '100%' }}>
            <Col span={4}>
              <Form.Item label="关键字" name="keyword">
                <Input placeholder="请输入关键字" onChange={() => queryData()} />
              </Form.Item>
            </Col>

            <Col
              span={4}
              className="basic-search-form-submit-btn"
              style={{ display: 'flex', justifyContent: 'flex-end' }}
            >
              <Button
                onClick={() => {
                  form.resetFields();
                  queryData();
                }}
              >                <UndoOutlined />

                重置
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" htmlType="submit" onClick={() => queryData()}>
                <SearchOutlined />
                查询
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };
  const actionRef = useRef<ActionType>();
  const [approveForm] = Form.useForm();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(40);
  const [dataArray, setDataArray] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [approveOpen, setApproveOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [displaySbyy, setDisplaySbyy] = useState(false);
  const [isOrder, setIsOrder] = useState(false);
  const [addShow, setAddShow] = useState(false);
  const [orderNum, setOrderNum] = useState(0);
  const [currentRow, setCurrentRow] = useState<any>();
  const [categoryTreeData, setCategoryTreeData] = useState([]);
  const [loadingTable, setLoadingTable] = useState(true);
  const [pagination, setPagination] = useState({
    current: page,
    pageSize: pageSize,
    position: ['bottomRight'],
    size: 'small',
    showSizeChanger: true,
    total: total,
  });
  const handleEdit = async (record) => {
    const res = await getSubSystem({subSysId:record.subSysId})
    setCurrentRow(res.data)
    setFileList([{...res.data.file, uid: res.data.file.id, name: res.data.file.fileName,status:'done',url:res.data.file.src}])
    setPicForm(res.data.file)
    form.setFieldValue('pic',res.data.file.fileName)
    form.setFieldValue('subSysName',res.data.subSysName)

    console.log(form.getFieldValue('pic'))
    setAddShow(true)
  };
  const generatTreeData = (data) => {
    data.map((item, index) => {
      data[index].value = item.id;
      data[index].title = item.name;
      if (item.children && item.children.length > 0) {
        generatTreeData(item.children);
      }
    });
    return data;
  };
  const getCategory = () => {
    const params = {
      type: 'photo',
    };
    //获取组list
    getPhoCatListWithoutSpe().then(async (res) => {
      const data = generatTreeData(res.data);
      data.unshift({
        id: 'all',
        title: '全部分类',
        name: 'all',
        value: 'all',
      });

      setCategoryTreeData(data);
    });
  };
  useEffect(() => {
    getCategory();
  }, []);
  const handleDelete = async (record: any) => {
    try {
      const res = await delSubSystem({ subSysId: record.subSysId });
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败' + error.response.data.message);
    }
    queryData();
  };

  useEffect(() => {
    queryData(true);
  }, [page, pageSize]);

  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    setPageSize(pagination.pageSize);
    setPagination({ ...pagination });
  };
  const queryData = async (pageChanged) => {
    setLoadingTable(true);
    let values = form.getFieldsValue();
    Object.keys(values).map((item) => {
      if (values[item] === 'all') delete values[item];
    });
    let params = {};
    if (!Object.values(values).every((i) => !i) && !pageChanged) {
      //搜索状态，page为1
      params = {
        page: 1,
        pageSize: pageSize,
        ...values
      };
    } else {
      //搜索状态
      params = {
        page: page,
        pageSize: pageSize,
        ...values

      };
    }

    const msg = await getSubSystemList(params, values);
    setDataArray(msg.data.list);
    let paginationNew = pageChanged
      ? {
        ...pagination,
        total: msg.data.total,
      }
      : {
        ...pagination,
        total: msg.data.total,
        current: 1,
      };
    setPagination(paginationNew);

    setLoadingTable(false);
  };
  const handleCancel = () => {
    setPreviewOpen(false);
    setApproveOpen(false);
    setDisplaySbyy(false);
  };
  const changeApprove = (values) => {
    console.log(values);
    const currentValue = values.target.value;
    if (currentValue === '0') setDisplaySbyy(true);
    else if (currentValue === '1') setDisplaySbyy(false);
  };

  const handleOrderOk = async () => {
    const params = {
      id: currentRow.id,
      pxh: orderNum,
    };
    const res = await changePhotoOrder(params);
    if (res.code == '0') {
      message.success('修改成功！');
      queryData();
    }
    setIsOrder(false);
  };


  const columns: ProColumns[] = [
    {
      title: '横幅缩略图',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'bannerSrc',
      render: (_, record) =>
        record.bannerSrc != null ? [<Image width={150}
                                           src={MNTPrefix + record.bannerSrc} />] : '',
    },
    {
      title: '系统名称',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'subSysName',
    },
    {
      title: '系统链接',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'subSysUrl',
    },

    {
      title: '创建时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdTime',
    },
    {
      title: '操作',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'id',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            handleEdit(record);
          }}
        >
          <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
            编辑
          </Button>
        </a>,
        <Popconfirm title="确定是否删除?" onConfirm={() => handleDelete(record)} key="delete">
          <a style={{ color: 'red' }}>
            <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
              删除
            </Button>
          </a>
        </Popconfirm>,
      ],
    },
  ];
  const resetForm = ()=>{
    console.log('reset');
    setCurrentRow({})
    form.setFieldValue('subSysName','')
    form.setFieldValue('link','')
    form.setFieldValue('pic','')
    setFileList([])
    setPicForm({})
  }

  return (
    <PageContainer>
      {_initSearchForm()}
      <ProTable
        search={false}
        loading={loadingTable}
        // headerTitle="视媒管理"
        actionRef={actionRef}
        rowKey="id"
        tableStyle={{ textAlign: 'center' }}
        options={false}
        pagination={pagination}
        dataSource={dataArray}
        onChange={handleTableChange}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setAddShow(true)
            }}
          >
            <PlusOutlined />
            发布子系统
          </Button>,
        ]}
        columns={columns}
        rowSelection={{
          onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            // setKeyLength(0)
          },
          // renderCell: () => "",
          // selectedRowKeys: selectedRowKey
        }}
      ></ProTable>
      <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
        <img
          alt="example"
          style={{
            width: '100%',
          }}
          src={previewImage}
        />
      </Modal>

      <ModalForm
        form={form}
        title="添加子系统"
        width="600px"
        layout={'horizontal'}
        {...formLayout}
        visible={addShow}
        onVisibleChange={bool=>{
          setAddShow(bool)
          console.log(currentRow,'currentRow');
          if(!bool) {
            resetForm()
          }
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        modalProps={{ destroyOnClose: true }}
        onFinish={async (value) => {
          const params = {...currentRow,...value,file:picForm}
          if(currentRow && currentRow.id){
            const success = await updateSubSystem(params);
            if (success) {
              message.success('编辑成功');
              setAddShow(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }else{
            const success = await addSubSystem(params);
            if (success) {
              message.success('新增成功');
              setAddShow(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }
          resetForm()
          queryData()
        }}
      >
        <ProFormText
          initialValue={currentRow?.subSysName}
          rules={[
            {
              required: true,
              message: '请输入系统名称！',
            }
          ]}
          width="md"
          name="subSysName"
          placeholder="请输入系统名称"
          label="系统名称"
        />

        <ProFormItem
          width="md"
          name="pic"
          initialValue={currentRow?.file?.fileName}
          rules={[
            {
              required: true,
              message: '请上传背景横幅！',
            },
          ]}
          label="背景横幅">

          <ImgUpload maxCount={1} url={'/api/v1/photo/uploadList'}
                     content={'点击修改图片'} form={form} fileList={fileList} setFileList={setFileList} />
        </ProFormItem>
      </ModalForm>


    </PageContainer>
  );
};
export default PicturenManagement;
